class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();

        vector<vector<int>> dp(m, vector<int>(n,0));
        int res = 0;

        for(int i = 0; i < n; i++)
        {
            dp[0][i] = matrix[0][i]=='0' ? 0 : 1;
            res = max(res, dp[0][i]);
        }
        for(int i = 0; i < m; i++)
        {
            dp[i][0] = matrix[i][0]=='0' ? 0 : 1;
            res = max(res, dp[i][0]);
        }
        
        for(int i = 1; i < m; i++)
        {
            for(int j = 1; j < n; j++)
            {
                if(matrix[i][j] == '0')
                    continue;

                int left_top = dp[i-1][j-1];
                int right_top = dp[i-1][j];
                int left_bottom = dp[i][j-1];
                dp[i][j] = min(left_bottom, min(left_top, right_top)) + 1;
                res = max(dp[i][j], res);
            }
        }

        return res*res;
    }
};